package com.cci.kangdao.cipFleet.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cci.kangdao.cipFleet.entity.ExternalCustomerESNT;
import com.cci.kangdao.cipFleet.service.ExternalCustomerESNTService;
import com.cci.kangdao.dao.DictionariesTDao;
import com.cci.kangdao.dto.BaseResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: joe
 * @company: CTY
 * @since: 2023/5/18 11:50
 * @version: V1.0
 **/
@RequestMapping("externalFleet")
@RestController
public class ExternalCustomerESNController {
    @Autowired
    private ExternalCustomerESNTService externalCustomerESNTService;
    @Autowired
    private DictionariesTDao dictionariesTDao;

    @RequestMapping("upholdUserIdESN.aspx")
    public BaseResponse upholdUserIdESN(@RequestBody List<ExternalCustomerESNT> list, @RequestHeader String token,
                                        @RequestHeader String source) {
        //验证token
        String externalFleet = dictionariesTDao.getListByDTableName("ExternalFleet");
        List<JSONObject> jsonObjectList = JSON.parseArray(externalFleet, JSONObject.class);
        boolean flag = jsonObjectList.stream().anyMatch(e -> {
            return e.getString("token").equals(token) && e.getString("source").equals(source);
        });
        if (!flag) {
            return BaseResponse.error(-99, "获取token信息失败");
        }
        //验证参数是否正确
        boolean paraFlag = list.stream().anyMatch(e -> StringUtils.isBlank(e.getESN()) || e.getUserId() == null);
        if (paraFlag) {
            return BaseResponse.error(-99, "esn为空或者userId为空");
        }
        //验证参数是否正确
        boolean esnFlag = list.stream().anyMatch(e -> !StringUtils.isNumeric(e.getESN()) || e.getESN().length() > 8);
        if (esnFlag) {
            return BaseResponse.error(-99, "esn格式不正确");
        }
        List<Integer> collect = jsonObjectList.stream().filter(e -> {
            return e.getString("token").equals(token) && e.getString("source").equals(source);
        }).map(e -> e.getInteger("type")).collect(Collectors.toList());
        return BaseResponse.success(externalCustomerESNTService.upholdUserIdESN(list, collect.get(0)));
    }
}
